package top.firejames.io.thread;

import top.firejames.io.SortTest;
import top.firejames.util.FileConstant;
import top.firejames.util.FileUtil;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @auther 夏浩
 * @creat 2021-09-2021/9/24-0:19
 */
public class ThreadIo {
    static int count = 0;

    public static synchronized   void addCount() {
        count++;
    }


    /**
     * 从指定的文件路径读入并且以指定的多线程数量去读取到指定的文件夹中
     *
     * @param sourcePath   数据读入路径
     * @param destPath     存放的文件夹的路径
     * @param allLines     数据总的行数
     * @param threadNumber 线程数
     */
    public static String[] readAndWrite(String sourcePath, String destPath, int allLines, int threadNumber) {
        ExecutorService executorService = Executors.newFixedThreadPool(threadNumber);
        //设置读文件开始的行数
        int startLine = 0;
        //设置读文件结束的行数
        int endLile = allLines / threadNumber;
        //保存存放的路径
        String pathAndFileName = destPath;
        String[] pathAndFileNameArray = new String[threadNumber];
        System.out.println("开始切割大文件为：" + threadNumber + "份....");
        int index = FileConstant.fileName;
        for (int i = 0; i < threadNumber; i++) {
            //生成文件路径
            pathAndFileName = destPath + "\\" + FileConstant.SLICE_FILE_PROFIX + String.valueOf(index++) + FileConstant.FILE_SUFFIX;
            pathAndFileNameArray[i] = pathAndFileName;
            int finalStartLine = startLine;
            int finalEndLile = endLile;
            String finalS = pathAndFileName;
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        //每个线程读取不同的行数到给出的文件夹中
                        FileUtil.LineNumberRead(sourcePath, finalS, finalStartLine, finalEndLile);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    addCount();
                    if (count >= threadNumber) {
                        executorService.shutdown();
                        System.out.println("切割完成");
                        SortTest.afterCut();
                    }
                    System.out.println(Thread.currentThread().getName() + "\t" + count + "readAndWrite");
                }
            });
            startLine = endLile + 1;
            endLile += allLines / threadNumber;
        }
        return pathAndFileNameArray;


    }


}
